package com.yxw.live_vod_boot.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxw.live_vod_backend_facade.feign.WithdrawalRecordFeignClient;
import com.yxw.live_vod_backend_facade.vo.WithdrawalRecordVO;
import com.yxw.live_vod_boot.dto.BalanceDetailAddDTO;
import com.yxw.live_vod_boot.dto.BalanceDetailQueryDTO;
import com.yxw.live_vod_boot.entity.YxBalanceDetailEntity;
import com.yxw.live_vod_boot.entity.YxLiveShopEntity;
import com.yxw.live_vod_boot.entity.YxOrderEntity;
import com.yxw.live_vod_boot.mapper.BalanceDetailMapper;
import com.yxw.live_vod_boot.mapper.OrderMapper;
import com.yxw.live_vod_boot.mapper.ShopMapper;
import com.yxw.live_vod_boot.service.BalanceDetailService;
import com.yxw.live_vod_boot.utils.PageUtils;
import com.yxw.live_vod_boot.vo.BalanceDetailVO;
import com.yxw.yxnet_cd_center.common.constant.CommonConstant;
import com.yxw.yxnet_cd_center.common.dto.PageVO;
import com.yxw.yxnet_cd_center.common.exception.BaseException;
import com.yxw.yxnet_cd_center.common.utils.BaseResult;
import com.yxw.yxnet_cd_center.common.utils.IdWorkerUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 店铺余额明细Service实现类
 * @author xiexuxin
 * @date 2024-01-03
 */
@Service
public class BalanceDetailServiceImpl extends ServiceImpl<BalanceDetailMapper, YxBalanceDetailEntity> implements BalanceDetailService {

    @Autowired
    private BalanceDetailMapper balanceDetailMapper;

    @Autowired
    private WithdrawalRecordFeignClient withdrawalRecordFeignClient;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ShopMapper shopMapper;

    /**
     * 新增余额明细
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBalanceDetail(BalanceDetailAddDTO dto) {
        YxBalanceDetailEntity balanceDetail = new YxBalanceDetailEntity();
        BeanUtils.copyProperties(dto, balanceDetail);
        if (dto.getType() == 0){
            BaseResult<WithdrawalRecordVO> result = getWithdrawalRecordById(dto.getWithdrawDepositId());
            WithdrawalRecordVO vo = result.getData();
            balanceDetail.setWithdrawDepositId(vo.getWithdrawDepositId());
            balanceDetail.setAmount("-" + vo.getAmount());
            balanceDetail.setShopId(vo.getShopId());
            balanceDetail.setShopName(vo.getShopName());
            balanceDetail.setMerchantId(vo.getMerchantId());
            balanceDetail.setMerchantName(vo.getMerchantName());
        }
        if (dto.getType() == 1){
            YxOrderEntity order = orderMapper.selectById(dto.getOrderId());
            YxLiveShopEntity shop = shopMapper.selectById(order.getShopId());
            balanceDetail.setOrderId(order.getOrderId());
            balanceDetail.setAmount("+" + order.getActualAmount());
            balanceDetail.setShopId(shop.getLiveShopId());
            balanceDetail.setShopName(shop.getShopName());
            if (NumberUtils.isParsable(shop.getMerchantId())){
                balanceDetail.setMerchantId(Long.parseLong(shop.getMerchantId()));
            }
            balanceDetail.setMerchantName(shop.getMerchantName());
        }
        balanceDetail.setType(dto.getType());
        balanceDetail.setStatus(CommonConstant.ZERO);
        balanceDetail.setTradingTime(new Date());
        balanceDetail.setTransactionNum(IdWorkerUtils.generateTransactionNumber());
        balanceDetail.setDetail(BalanceDetailMapper.BALANCE_DETAIL[dto.getDetail()]);
        balanceDetail.setRemark(dto.getRemark());
        int rows = balanceDetailMapper.insert(balanceDetail);
        if (rows != 1) {
            throw new BaseException("添加余额明细数据失败，服务器忙，请稍后再试！");
        }
    }

    /**
     * 获取提现记录详情
     * @param id
     * @return
     */
    @Override
    public BaseResult<WithdrawalRecordVO> getWithdrawalRecordById(Long id) {
        return withdrawalRecordFeignClient.getWithdrawalRecordById(id);
    }

    @Override
    public PageVO<List<BalanceDetailVO>> getBalanceDetailList(BalanceDetailQueryDTO dto) {
        Page<BalanceDetailVO> page = new Page<>(dto.getCurrPage(), dto.getPageSize());
        List<BalanceDetailVO> list = balanceDetailMapper.getBalanceDetailList(page, dto);
        Map<String, List<BalanceDetailVO>> map = new HashMap<>();
        List<List<BalanceDetailVO>> result = new ArrayList<>();
        for (BalanceDetailVO vo : list) {
            String yearMonth = vo.getYearMonth();
            if (map.containsKey(yearMonth)) {
                map.get(yearMonth).add(vo);
            } else {
                List<BalanceDetailVO> newList = new ArrayList<>();
                newList.add(vo);
                map.put(yearMonth, newList);
                result.add(newList);
            }
            double totalAmountIncrease = Double.parseDouble(vo.getTotalAmountIncrease());
            String totalAmountIncreaseString = String.format("%.2f", totalAmountIncrease);
            if (totalAmountIncrease > 0) {
                totalAmountIncreaseString = "+" + totalAmountIncreaseString;
            }
            vo.setTotalAmountIncrease(totalAmountIncreaseString);
            double totalAmountReduce = Double.parseDouble(vo.getTotalAmountReduce());
            String totalAmountReduceString = String.format("%.2f", totalAmountReduce);
            if (totalAmountReduce > 0) {
                totalAmountReduceString = "-" + totalAmountReduceString;
            }
            vo.setTotalAmountReduce(totalAmountReduceString);
        }
        for (List<BalanceDetailVO> newList : result) {
            Collections.sort(newList, Comparator.comparing(BalanceDetailVO::getTradingTime).reversed());
        }
        Collections.reverse(result);
        return PageUtils.get(page, result);
    }

    @Override
    public BalanceDetailVO getBalanceDetailById(Long id) {
        YxBalanceDetailEntity balanceDetail = balanceDetailMapper.selectById(id);
        BalanceDetailVO vo = new BalanceDetailVO();
        BeanUtils.copyProperties(balanceDetail, vo);
        return vo;
    }


}
